<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图d -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表区 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', 'vcenter', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  disable-transitions
                  @close="removeRightById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级/三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      disable-transitions
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      disable-transitions
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- 解析jsonp格式 -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope" width="300px">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoleShow(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed()"
    >
      <!-- 内容区 -->
      <el-form
        :model="addRoleInfo"
        :rules="roleRules"
        ref="addRoleRef"
        label-width="100px"
      >
        <!-- 这里的prop应与addRoleInfo中的名字相同,prop不止与rules有关，还与ref有关 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editeRoleDialogClosed()"
    >
      <!-- 内容区 -->
      <el-form
        :model="editRoleInfo"
        :rules="roleRules"
        ref="editRoleRef"
        label-width="100px"
      >
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="editRoleInfo.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRightDialogClosed()"
    >
      <!-- 内容区(树形控件) -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      roleList: [],
      // 所有权限树形列表
      rightsList: [],
      // 添加角色数据
      addRoleInfo: {
        roleName: '',
        roleDesc: '',
      },
      //编辑角色数据
      editRoleInfo: {
        roleId: '',
        roleName: '',
        roleDesc: '',
      },
      //角色验证规则
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
      },
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      setRoleDialogVisible: false,
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的节点id值
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色失败！')
      }
      this.roleList = res.data
      //console.log(res);
    },
    //监听用户添加对话框的关闭事件
    addRoleDialogClosed() {
      this.$refs.addRoleRef.resetFields()
    },
    //添加角色函数
    addRoles() {
      this.$refs.addRoleRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleInfo)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        // 隐藏用户对话框
        this.addRoleDialogVisible = false
        // 重新获取用户列表
        this.getRoleList()
        //console.log(res);
      })
    },
    //编辑角色
    async editRoleShow(id) {
      const { data: res } = await this.$http.get('roles/' + id, {
        params: this.editRoleInfo,
      })
      //console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败！')
      }
      this.editRoleInfo = res.data
      this.editRoleDialogVisible = true
    },
    //监听用户添加对话框的关闭事件
    editRoleDialogClosed() {
      this.$refs.editRoleRef.resetFields()
      this.editRoleDialogVisible = false
    },
    // 编辑角色
    editRoles() {
      this.$refs.editRoleRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `roles/${this.editRoleInfo.roleId}`,
          {
            roleName: this.editRoleInfo.roleName,
            roleDesc: this.editRoleInfo.roleDesc,
          }
        )
        //console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error('编辑角色失败！')
        }
        this.$message.success('编辑角色成功！')
        this.getRoleList()
        this.editRoleDialogVisible = false
      })
    },
    editeRoleDialogClosed() {
      this.$refs.editRoleRef.resetFields()
    },
    //弹出是否确认删除的提示,warningStr表示需要修改的提示语
    async showRemoveConfirm(warningStr) {
      const confirmRes = await this.$confirm(
        `此操作将永久删除该${warningStr}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果确认，则会返回字符串confirm
      // 如果取消，则会返回cancel
      return confirmRes
    },
    // 删除角色
    async deleteRole(id) {
      const confirmMoveRole = await this.showRemoveConfirm('角色')
      if (confirmMoveRole !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRoleList()
    },
    // 权限tag删除
    async removeRightById(role, rightid) {
      const confirmRes = await this.showRemoveConfirm('权限')
      if (confirmRes !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightid}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      role.children = res.data
      this.$message.success('删除权限成功！')
    },
    //展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('获取所有权限列表失败！')
      }
      this.rightsList = res.data
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defKeys)
      this.setRoleDialogVisible = true
    },
    // 通过递归的形式，获取指定角色下的三级id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRoleList()
      this.setRoleDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>